import {getAccessToken} from '@/utils/token';

export const addAuthorization = (config: any) => {
  // set headers token
  const authorization = config.headers['Authorization'];
  if (!authorization && authorization !== false) {
    const accessToken = getAccessToken();
    if (accessToken) {
      config.headers['Authorization'] = 'Bearer ' + accessToken;
    }
  }
};

export const getResponse = (res: any) => {
  const resp = res.data || {} as any;
  if (res.status !== undefined && res.status !== null && res.status !== 200) {
    const message = resp.message || res.message || res.statusText || '未知错误，请重试！';
    return {
      status: res.status,
      message: message,
      data: resp.data
    };
  } else if (resp.status !== undefined && resp.status !== null && resp.status !== 200) {
    const message = resp.message || res.message || res.statusText || '未知错误，请重试！';
    return {
      status: resp.status,
      message: message,
      data: resp.data
    };
  }
  return resp;
};

export const getError = (error: any) => {
  const message = error.message || '未知错误，请重试！';
  if (error.status !== undefined && error.status !== null) {
    return {
      status: error.status,
      message: message,
      data: error
    };
  }
  return {
    status: -999,
    message: message,
    data: error
  };
};

export const gotoLogin = (res) => {
  const gotoLogin = res?.config?.headers?.gotoLogin;
  if (gotoLogin !== undefined && gotoLogin !== null) {
    return gotoLogin;
  }
  return true;
};